package com.program.wechatmall.TypeHandler;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;


import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author: chengxin
 * @Date :  2020/8/31 19:53
 * @Version 1.0
 */
@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ArrayToStringTypeHandler extends BaseTypeHandler<Integer[]> {

    ObjectMapper objectMapper = new ObjectMapper();
    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Integer[] integers, JdbcType jdbcType) throws SQLException {
        String string = objectMapper.writeValueAsString(integers);
        preparedStatement.setString(i, string);
    }

    @SneakyThrows
    @Override
    public Integer[] getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String result = resultSet.getString(s);
        return parse(result);
    }

    @SneakyThrows
    @Override
    public Integer[] getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String result = resultSet.getString(i);
        return parse(result);
    }

    @SneakyThrows
    @Override
    public Integer[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String result = callableStatement.getString(i);
        return parse(result);
    }

    private Integer[] parse(String result) throws IOException {
        return objectMapper.readValue(result, Integer[].class);
    }
}
